#include "error.h"

#include <QFile>
#include <QDir>
#include <QDateTime>

Error* Error::errorInstance=0;

Error::Error(QObject *parent) :
    QObject(parent)
{
    init();                                                                                               //create log dir
    QString file=QString(LOG_FILE).arg(QDateTime::currentDateTime().toString(FILE_NAME_DATE_FORMAT));    //set the file name with the current time
    QFile* fileHandler=new QFile(QString(LOG_DIR)+file);
    fileHandler->open(QIODevice::WriteOnly);
    stream=new QTextStream(fileHandler);                                                                //write to the default log file
}

Error::~Error()
{
    delete stream;
    delete errorInstance;   //possible???
}

Error *Error::getInstance()
{
    if(!errorInstance)
        errorInstance=new Error();
    return errorInstance;
}

void Error::msgOut(QtMsgType type, const char *msg)
{
    Error *er=Error::getInstance(); //get an error instance
    QMessageBox msgBox;

    switch(type)
    {
    case QtDebugMsg:
        std::cerr<<msg<<std::endl;
        break;
    case QtWarningMsg:
        er->getStream()<<"Warning  - "<<msg<<endl;
        msgBox.setText(msg);
        msgBox.exec();                              //show a message box
        break;
    case QtCriticalMsg:
        er->getStream()<<"Critical - "<<msg<<endl;
        msgBox.setText(msg);
        msgBox.exec();                              //show a message box
        break;
    case QtFatalMsg:
        er->getStream()<<"Fatal    - "<<msg<<endl;
        msgBox.setText(msg);
        msgBox.exec();                              //show a message box
        abort();
    }
}

QTextStream& Error::getStream()
{
    return *stream;
}

void Error::init()
{
    QDir dir;
    dir.mkdir(LOG_DIR);
}
